<style>
    #QR-div{
        display: flex;
        flex-direction: column;
        text-align: center;
        background-color: transparent;
    }
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md15">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md12">
                            <div class="layui-card">
                                <div class="layui-card-header">学生激活码管理</div>
                                <div class="layui-card-body">
                                    <table id="codeTable" lay-filter="codeTable"></table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<div class="layui-content" id="activeBox" style="display: none">
    <div class="layui-card" style="height:100%">
        <div class="layui-card-header">生成教师激活码</div>
        <form class="layui-form layui-card-body" action="">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">*个数：</label>
                    <div class="layui-input-inline">
                        <input name="codeNumber" class="layui-input" placeholder="/个" id="codeNumber" type="number"
                               autocomplete="off" lay-verify="codeNumber">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">*使用次数：</label>
                    <div class="layui-input-inline">
                        <input name="useNumber" class="layui-input" placeholder="/次" id="useNumber" type="number"
                               autocomplete="off" lay-verify="useNumber">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">*有效期：</label>
                    <div class="layui-input-inline">
                        <input name="range_num" class="layui-input" placeholder="/天" id="range_num" type="number"
                               autocomplete="off" lay-verify="time">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select id="range_time"
                                style="font-size: 28px; text-align: right; font-weight: bold; width: 10%;">
                            <option value="day">天</option>
                            <option value="month">月</option>
                            <option selected="selected" value="year">年</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注：</label>
                <div class="layui-input-block">
                    <input name="desc" class="layui-input" type="text" id="desc" placeholder="请输入备注"
                           autocomplete="off"
                           lay-verify="desc">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block" style="float: right;right: 50px">
                    <a class="layui-btn layui-btn-blue" id="addActive" onclick="createCode()" lay-submit
                       lay-filter="createCode">创建学生端激活码</a>
                </div>
            </div>
        </form>
    </div>
    <div class="layui-card-body">
        <table id="createCode" lay-filter="createCode"></table>
    </div>
</div>
<div id="QR-div" style="display: none">


    <div id="QRbox">
    </div>
    <a class="layui-btn layui-btn layui-btn-sm" onclick="doScreenShot()"><i class="layui-icon">&#xe601;</i> 下载</a>
</div>
<script id="toolbarDemo" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" onclick="addActive()"><i class="layui-icon">&#xe608;</i>
            创建学生激活码
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="refresh()"><i class="layui-icon">&#xe9aa;</i>
            刷新
        </button>
    </div>
</script>
<script type="text/javascript" src="js/jquery.qr.min.js"></script>
<script type="text/javascript" src="js/html2canvas.min.js"></script>

<script>
    var startInter = api.codeApi;
    var type = /^[1-9]\d*$/;
    $(document).ready(function () {

        $("#useNumber").bind('input propertychange', function () {
            var useNumber = $("#useNumber").val();

            if (!type.test(useNumber)) {
                $("#useNumber").val("");
                layer.tips('次数必须为正整数哦', '#useNumber');
                return false;
            }
            else {
                layer.tips('输入正确', '#useNumber');
            }

        });

        $("#range_num").bind('input propertychange', function () {
            var range_num = $("#range_num").val();
            if (!type.test(range_num)) {
                $("#range_num").val("");
                layer.tips('有效期必须为正整数哦', '#range_num');
            }
            else {
                layer.tips('输入正确', '#range_num');
            }
        });
        $("#codeNumber").bind('input propertychange', function () {
            var codeNumber = $("#codeNumber").val();
            if (!type.test(codeNumber)) {
                $("#codeNumber").val("");
                layer.tips('个数必须为正整数哦', '#codeNumber');
            }
            else {
                layer.tips('输入正确', '#codeNumber');
            }
        });

        layui.use(['form', 'table', 'laydate'], function () {
            var form = layui.form
                , layer = layui.layer
                , laydate = layui.laydate;
            laydate.render({
                elem: '#delay',
                type: 'datetime'
            });

            //监听单选框的值
            form.on("radio(code)", function (data) {
                audio = data.value;
                getStartUp();

            });
            //监听筛选的选择框
            form.on("select(cs)", function (data) {
                cs = data.value;
                getStartUp();
            });
            //监听active的值
            form.on('select(active)', function (data) {
                if (data.value == "10") {
                    active = "";
                }
                else {
                    active = data.value;
                }

                getStartUp();
            });

            $("#keyword").bind('input propertychange', function () {
                keyword = $("#keyword").val();
                getStartUp();
            });
            form.render();
        });
        getStartUp();
    });

    function addActive() {
        personWin = layer.open({
            type: 1,
            shade: false,
            area: ['60%', '75%'], //宽高
            title: false, //不显示标题
            content: $('#activeBox'),
            cancel: function () {
                document.getElementById("activeBox").style.display = "none";
                getStartUp();
            }
        });
    }

    function refresh() {
        getStartUp();
    }

    //获取启动次数的数据
    function getStartUp() {
        layui.use('table', function () {
            var table = layui.table;
            //第一个实例
            table.render({
                elem: '#codeTable'
                , url: "api/coList.php" //数据接口
                , title: '激活码列表数据'
                , page: true //开启分页
                , toolbar: "#toolbarDemo"
                , method: 'POST'
                , limit: 100
                , limits: [20, 40, 60, 100, 200]

                , where: {
                    action: "getStudentCode",
                }
                , cols: [[ //表头
                    {field: 'index', title: '序号', fixed: 'left', type: 'numbers', toolbar: "#tableId"}
                    , {field: 'active_code', title: '激活码', width: 180}
                    , {field: 'used_times', title: '被使用次数', width: 100}
                    , {field: 'info', title: '说明', width: 100}
                    , {field: 'create_time', title: '创建时间', width: 170, toolbar: "#createTime"}
                    , {field: 'Exptime', title: '过期时间', width: 170, toolbar: "#exptime"}
                    , {field: 'max_use_times', title: '最多使用次数'}
                    , {field: '', toolbar: '#barDemo', title: '操作'}
                ]]
                , done: function (res, curr, count) {
                    if (res.count == 0) {
                        layer.msg("没有符合条件的数据哦");
                    }
                }

            });

            table.on('tool(codeTable)', function (obj) {
                var data = obj.data, layEvent = obj.event;
                if (layEvent == 'showImg') {

                    createCodeImg(data.active_code);

                }


            })


        });

    }

    //延期
    function delay(val) {
        $entTime = to_date(val.endtime);
        delayId = val.yid;
        $("#delayTime").html("到期时间：" + $entTime);
        $("#delay").val($entTime);
        preDelay = $entTime;
        personWin = layer.open({
            type: 1,
            shade: false,
            area: ['50%', '30%'], //宽高
            title: false, //不显示标题
            content: $('#delayBox'),
            cancel: function () {
                document.getElementById("delayBox").style.display = "none";
            }
        });

    }


    //、生成教师激活码
    function createCode() {

        $desc = $("#desc").val();
        var range_num = $("#range_num").val();
        var range_time = $("#range_time").val();
        var num = $("#useNumber").val();//生成数量
        var codeNumber = $("#codeNumber").val();
        if (!type.test(num)) {
            $("#useNumber").val("");
            layer.tips('次数必须为正整数哦', '#useNumber');
            return false;
        }

        else if (!type.test(range_num)) {
            layer.tips('有效期必须为正整数哦', '#range_num');
            return false;
        }

        else {

            layui.use('table', function () {
                var table = layui.table;
                //第一个实例
                table.render({
                    elem: '#createCode'
                    , url: "api/coList.php" //数据接口
                    , title: '新增学生激活码'
                    , method: 'POST'
                    , where: {
                        "action": "createStudentCode",
                        "info_comments": $desc,
                        "Much": range_num,
                        "shiJian": range_time,
                        "UserNumber": num,
                        "CodeNumber": codeNumber,
                    }
                    , cols: [[ //表头
                        {field: 'index', title: '序号', fixed: 'left', type: 'numbers', toolbar: "#tableId"}
                        , {field: 'active_code', title: '激活码'}
                        , {field: 'info', title: '说明', width: 100}
                        , {field: 'max_use_times', title: '最多使用次数'}
                    ]]
                    , done: function (res, curr, count) {
                        if (res.count == 0) {
                            layer.msg("没有符合条件的数据哦");
                        }
                    }
                    ,
                });

            });
        }

    }

    //二维码生成
    function createCodeImg(val) {
        var str = val;
        $('#QRbox').qrcode(str);
        $("#QRbox").empty();
        var str = toUtf8(str);
        $("#QRbox").qrcode({

            render: "table",

            width: 200,

            height: 200,

            text: str

        });

        layer.open({
            type: 1,
            shade: false,
            title: false, //不显示标题
            content: $('#QR-div'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function () {
                $("#QR-div").css({"display":"none"});
                $("#QRbox").empty();
            }
        });
    }


    function toUtf8(str) {

        var out, i, len, c;

        out = "";

        len = str.length;

        for (i = 0; i < len; i++) {

            c = str.charCodeAt(i);

            if ((c >= 0x0001) && (c <= 0x007F)) {

                out += str.charAt(i);

            } else if (c > 0x07FF) {

                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));

                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));

                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

            } else {

                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));

                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

            }

        }

        return out;

    }

    //保存图片
    //点击截图
    function doScreenShot() {
        html2canvas($("#QRbox"), {
            onrendered: function (canvas) {
                canvas.id = "mycanvas";
                var mainwh = $("#QRbox").width();
                var mainhg = $("#QRbox").height();
                var img = convertCanvasToImage(canvas);
                // $("#QRbox").append(img) //添加到展示图片div区域
                img.onload = function () {
                    img.onload = null;
                    canvas = convertImageToCanvas(img, 0, 0, 300, 200); //设置图片大小和位置
                    img.src = convertCanvasToImage(canvas).src;
                    $(img).css({
                        background: "#fff"
                    });
                    //调用下载方法
                    if (browserIsIe()) { //假如是ie浏览器
                        DownLoadReportIMG(img.src);
                    } else {
                        download(img.src)
                    }
                }
            }
        });
    }

    //绘制显示图片
    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.src = canvas.toDataURL("image/png"); //获得图片地址
        return image;
    }

    //生成canvas元素，相当于做了一个装相片的框架
    function convertImageToCanvas(image, startX, startY, width, height) {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0, 0, 300, 200); //在这调整图片中内容的显示（大小,放大缩小,位置等）
        return canvas;
    }

    function DownLoadReportIMG(imgPathURL) {
        //如果隐藏IFRAME不存在，则添加
        if (!document.getElementById("IframeReportImg"))
            $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" onload="DoSaveAsIMG();" width="0" height="0" src="about:blank"></iframe>').appendTo("body");
        if (document.all.IframeReportImg.src != imgPathURL) {
            //加载图片
            document.all.IframeReportImg.src = imgPathURL;
        }
        else {
            //图片直接另存为
            DoSaveAsIMG();
        }
    }

    function DoSaveAsIMG() {
        if (document.all.IframeReportImg.src != "about:blank")
            window.frames["IframeReportImg"].document.execCommand("SaveAs");
    }

    // 另存为图片
    function download(src) {
        var $a = $("<a></a>").attr("href", src).attr("download", "img.png");
        $a[0].click();
    }

    //判断是否为ie浏览器
    function browserIsIe() {
        if (!!window.ActiveXObject || "ActiveXObject" in window)
            return true;
        else
            return false;
    }
</script>
<!--//到期时间-->
<script type="text/html" id="exptime">
    {{#  if(d.Exptime !=undefined){ }}
    <a style="color: #787878" class="layui-table-link">{{d.Exptime}}</a>
    {{#  } }}
</script>
<script type="text/html" id="createTime">
    {{#  if(d.create_time !=undefined){ }}
    <a style="color: #787878" class="layui-table-link">{{d.create_time}}</a>
    {{#  } }}
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="showImg"><i class="layui-icon">&#xe64a;</i>查看二维码</a>
</script>